<?php

class SessionsController extends Controller
{
	public function actionCreate()
  {
    $username = $_POST['username'];
    $password = md5($_POST['password']);
		$user = Users::model()->find('username = :username AND password = :password AND member_id = 1', array(':username' => $username, ':password' => $password ));

    // if user is exist && has been approved & not expired
    if($user && $user->status == Users::STATUS_APPROVED && strftime('%Y') <= $user->expired_date)
    {
      // check if expired date is imminent
      $redirect2 = false;
			date_default_timezone_set('Asia/Jakarta');
			
			$date1 = new DateTime($user->expired_date);
			$date2 = new DateTime(date('Y-m-d', time()));
			
			// $date1 = new DateTime('2009-08-12');
			// $date2 = new DateTime('2009-04-14');
			
      // $diff = abs(strtotime($user->expired_date) - strtotime(date('Y-m-d', time())));
      $diff = $date1->diff($date2);
      $diff = (($diff->format('%y') * 12) + $diff->format('%m'));
			// echo $diff;
			// exit;
			
      if((int)$diff <= 5){ $redirect2 = true; }
		
      $session = new CHttpSession;
      $session->open();
      $session['id'] = $user->id;
      $session['member_id'] = $user->member_id;
      $session['username'] = $user->name;

      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'Login Successful.');
      			
      if($redirect2 == false){
        $this->redirect(bu("members"));
      }else{
        $this->redirect(bu("users/extend"));
      }
    }
    else if($user && $user->status == Users::STATUS_INACTIVE)
    {
      $this->redirect(bu("/?notif=status_inactive"));
    }
    else if($user && $user->status == Users::STATUS_PENDING)
    {
      $this->redirect(bu("/?notif=status_pending"));
    }
    else
    {
      $this->redirect(bu("/?notif=no_member"));
    }
    // */
	}

	public function actionDestroy()
	{
		Yii::app()->session->clear();
		Yii::app()->session->destroy();
    $this->redirect(bu());
	}

	public function actionUpdate()
	{
		$this->render('update');
	}
}